package com.uzai.console.service.alipaydetail.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.device.*;
import com.uzai.common.enums.DeviceAuthTypeEnum;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.PaymentTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.AliPayConfig;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CommonConstant;
import com.uzai.console.dto.alipaydetail.AlipayDetailAlipayUrlDao;
import com.uzai.console.dto.alipaydetail.AlipayDetailCreateDto;
import com.uzai.console.dto.alipaydetail.AlipayDetailQuery;
import com.uzai.console.dto.alipaydetail.TransUniTransferDto;
import com.uzai.console.dto.device.deviceauth.DeviceAuthQuery;
import com.uzai.console.dto.feign.deviceauth.MobileDeviceAuthAdd;
import com.uzai.console.entity.*;
import com.uzai.console.entity.wxpubmanage.WxpubInfoEntity;
import com.uzai.console.enums.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.alipaydetail.AlipayDetailService;
import com.uzai.console.service.deviceauth.DeviceAuthService;
import com.uzai.console.service.feign.ClientApiService;
import com.uzai.console.service.kuizhan.KuaiZhanService;
import com.uzai.console.service.ratelimit.RatelimitService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoSyncService;
import com.uzai.console.vo.alipaydetail.AlipayDetailCreateVo;
import com.uzai.console.vo.alipaydetail.AlipayDetailInfoVo;
import com.uzai.console.vo.alipaydetail.AlipayTradeQueryVo;
import com.uzai.console.vo.alipaydetail.businessinfo.*;
import com.uzai.console.vo.kuaizhan.CreateSiteVo;
import com.uzai.common.utils.Math;

import com.uzai.console.vo.kuaizhan.PublishPageVo;
import com.uzai.console.vo.kuaizhan.PublishSiteVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/***
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class AlipayDetailServiceImpl implements AlipayDetailService {

    Logger logger = LoggerFactory.getLogger(AlipayDetailServiceImpl.class);

    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private AlipayDetailMapper alipayDetailMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private DeviceAuthMapper deviceAuthMapper;
    @Autowired
    private DeviceAuthDetailMapper deviceAuthDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private ProductAuthMapper productAuthMapper;
    @Autowired
    private ProductAuthDetailMapper productAuthDetailMapper;
    @Autowired
    private SysDomainMapper sysDomainMapper;
    @Autowired
    private KuaiZhanService kuaiZhanService;
    @Autowired
    private SysDomainDetailMapper sysDomainDetailMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;
    @Autowired
    private AliPayConfig aliPayConfig;
    @Autowired
    private UzaiConsoleSysConfig sysConfig;
    @Autowired
    private DeviceWechatInfoSyncService deviceWechatInfoSyncService;
    @Autowired
    private DeviceProductMapper deviceProductMapper;
    @Autowired
    private DevicePriceMapper devicePriceMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WxpubInfoMapper wxpubInfoMapper;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private DeviceAuthService deviceAuthService;
    @Autowired
    private DeviceTiktokInfoMapper deviceTiktokInfoMapper;
    @Autowired
    private DingWarningGroupMapper dingWarningGroupMapper;
    @Autowired
    private DingWarningGroupDetailMapper dingWarningGroupDetailMapper;
    @Autowired
    private ClientApiService clientApiService;


    /**
     * 查询支付宝交易记录列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetailQuery
     * @return null
     */
    public Page<AlipayDetailInfoVo> findAlipayDetailList(AlipayDetailQuery alipayDetailQuery){
        //新建返回到页面的LIST对象
        List<AlipayDetailInfoVo> alipayDetailInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<AlipayDetail> page = new Page<>();
        alipayDetailQuery.convert(page);
        ArrayList<AlipayDetail> alipayDetailList =  alipayDetailMapper.findByList(page, alipayDetailQuery);
        if(alipayDetailList != null && alipayDetailList.size() > 0){
            for (AlipayDetail alipayDetail : alipayDetailList){
                AlipayDetailInfoVo alipayDetailInfoVo = new AlipayDetailInfoVo();
                BeanUtils.copyProperties(alipayDetail, alipayDetailInfoVo);

                AlipayStatusEnum alipayStatusEnum = AlipayStatusEnum.getById(alipayDetail.getStatus());
                if(alipayStatusEnum != null){
                    alipayDetailInfoVo.setStatusName(alipayStatusEnum.getDesc());
                }
                AlipayTypeEnum alipayTypeEnum = AlipayTypeEnum.getById(alipayDetail.getType());
                if(alipayTypeEnum != null){
                    if(StringUtils.isNotBlank(alipayDetail.getSubtype())){//子交易类型
                        AlipaySubtypeEnum alipaySubtypeEnum = AlipaySubtypeEnum.getByKey(alipayDetail.getSubtype());
                        if(alipaySubtypeEnum != null){
                            alipayDetailInfoVo.setTypeName(alipayTypeEnum.getDesc() + "(" + alipaySubtypeEnum.getDesc() + ")");
                        }else{
                            alipayDetailInfoVo.setTypeName(alipayTypeEnum.getDesc());
                        }
                    }else{
                        alipayDetailInfoVo.setTypeName(alipayTypeEnum.getDesc());
                    }
                }
                alipayDetailInfoVoList.add(alipayDetailInfoVo);
            }
        }
        //返回到页面分页对象
        Page<AlipayDetailInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(alipayDetailInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询支付宝支付页面信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetailAlipayUrlDao
     * @return null
     */
    public AlipayDetailCreateVo findAlipayUrl(AlipayDetailAlipayUrlDao alipayDetailAlipayUrlDao){

        AlipayDetailCreateVo alipayDetailCreateVo = new AlipayDetailCreateVo();

        if(alipayDetailAlipayUrlDao.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        AlipayDetail alipayDetail = alipayDetailMapper.selectById(alipayDetailAlipayUrlDao.getId(), alipayDetailAlipayUrlDao.getMerId());
        if(alipayDetail == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该支付记录不存在");
        }
        alipayDetailCreateVo.setAlipayUrl(alipayDetail.getAlipayUrl());

        return alipayDetailCreateVo;
    }

    /**
     * 支付宝生产二维码支付
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetailCreateDto
     * @return null
     */
    public String createAlipayDetail(AlipayDetailCreateDto alipayDetailCreateDto){
        //返回支付页面地址
        String alipayUrl = "";
        String aliPayAppId = sysConfigMapper.selectByKey("aliPayAppId");
        String aliPayAppPriKey = sysConfigMapper.selectByKey("aliPayAppPriKey");
        try{
            //构造client(证书访问)
            CertAlipayRequest certAlipayRequest = aliPayConfig.getCertAlipayRequest(aliPayAppId, aliPayAppPriKey);
            //客户端订单客户端
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

            request.setNotifyUrl(sysConfig.getConsoleNetAddress() + aliPayConfig.getNOTIFY_URL());
            request.setReturnUrl(sysConfig.getConsoleNetAddress() + aliPayConfig.getRETURN_URL());
            //request.setNotifyUrl("");
            //request.setReturnUrl("");
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", alipayDetailCreateDto.getOutTradeNo());
            bizContent.put("total_amount", alipayDetailCreateDto.getTotalAmount());
            bizContent.put("subject", alipayDetailCreateDto.getSubject());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            bizContent.put("timeout_express", CommonConstant.ALIPAY_TRADE_TIMEOUT_EXPRESS + "m"); //订单生效时间 2分钟
            request.setBizContent(bizContent.toString());

            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            //System.out.println(response.getBody());
            if(response.isSuccess()){
                alipayUrl = response.getBody();
            } else {
                logger.error("调用支付宝生成账单失败,error={}", response.getSubMsg());
            }
        }catch (Exception e){
            logger.error("调用支付宝生成账单失败,error={}", e.getMessage());
        }
        return alipayUrl;
    }

    /**
     * 支付宝单笔转账
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param transUniTransferDto
     * @return null
     */
    public Boolean transUniTransfer(TransUniTransferDto transUniTransferDto){

        Boolean result = false;

        try{
            String aliPayAppId = sysConfigMapper.selectByKey("aliPayAppId");
            String aliPayAppPriKey = sysConfigMapper.selectByKey("aliPayAppPriKey");

            //构造client(证书访问)
            CertAlipayRequest certAlipayRequest = aliPayConfig.getCertAlipayRequest(aliPayAppId, aliPayAppPriKey);
            //客户端订单客户端
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            model.setOutBizNo(transUniTransferDto.getOutTradeNo());
            model.setRemark(transUniTransferDto.getSubject());
            model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
            model.setBizScene("DIRECT_TRANSFER");
            Participant payeeInfo = new Participant();
            payeeInfo.setIdentity(transUniTransferDto.getAlipayUserId());
            payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
            payeeInfo.setName(transUniTransferDto.getAlipayUserName());
            model.setPayeeInfo(payeeInfo);
            model.setTransAmount(String.valueOf(transUniTransferDto.getTotalAmount()));
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
            model.setOrderTitle(transUniTransferDto.getSubject());
            request.setBizModel(model);
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                logger.info("调用支付宝单笔调用成功");
                result = true;
            } else {
                logger.info("调用支付宝单笔调用失败");
                result = false;
            }
        }catch (Exception e){
            logger.error("调用支付宝单笔转账失败,error={}", e.getMessage());
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用支付宝单笔转账失败");
        }
        return result;
    }

    /**
     * 处理支付宝账单业务类型
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param paramsMap
     * @return null
     */
    @Transactional
    public void dealAlipayDetail(Map<String, String> paramsMap){

        String out_trade_no = paramsMap.get("out_trade_no");
        String sub_code = paramsMap.get("sub_code");
        String sub_msg = paramsMap.get("sub_msg");
        String ali_trade_no = paramsMap.get("trade_no");
        String seller_id = paramsMap.get("seller_id");
        String trade_status = paramsMap.get("trade_status");

        AlipayDetail alipayDetail = alipayDetailMapper.selectByTradeno(out_trade_no);
        if(alipayDetail == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付宝交易记录不存在");
        }

        Integer now = DateUtil.getNowTime();
        if("TRADE_SUCCESS".equals(trade_status)){ //订单成功
            if(alipayDetail != null && alipayDetail.getStatus().intValue() == AlipayStatusEnum.WAIT_BUYER_PAY.getId()){
                //订单状态为等待付款状态，才执行业务操作
                if(alipayDetail.getStatus().intValue() == AlipayStatusEnum.WAIT_BUYER_PAY.getId().intValue()){
                    dealBunisess(alipayDetail);
                }
                //修改支付宝账单状态为付款成功状态
                alipayDetail.setSubCode(sub_code);
                alipayDetail.setSubMsg(sub_msg);
                alipayDetail.setAliTradeNo(ali_trade_no);
                alipayDetail.setSellerId(seller_id);
                alipayDetail.setStatus(AlipayStatusEnum.TRADE_SUCCESS.getId());
                alipayDetail.setUpdateTime(now);
                int i = alipayDetailMapper.updateByIdSelective(alipayDetail);
                if(i != 1){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改支付宝交易记录失败");
                }
            }
        }else if("TRADE_CLOSED".equals(trade_status)){ //订单关闭
            //修改支付宝账单状态为付款成功状态
            alipayDetail.setSubCode("TRADE_HAS_CLOSE");
            alipayDetail.setSubMsg("交易已经关闭");
            alipayDetail.setAliTradeNo(ali_trade_no);
            alipayDetail.setSellerId(seller_id);
            alipayDetail.setStatus(AlipayStatusEnum.TRADE_CLOSED.getId());
            alipayDetail.setUpdateTime(now);
            int i = alipayDetailMapper.updateByIdSelective(alipayDetail);
            if(i != 1){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改支付宝交易记录失败");
            }
        }
    }

    /**
     * 处理支付宝订单业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealBunisess(AlipayDetail alipayDetail){
        if(alipayDetail.getType().intValue() == AlipayTypeEnum.DEVICE_MOBILE_ADD.getId()){//移动端机器人增加
            dealDeviceAddBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.DEVICE_PC_AUTH.getId()             //电脑端机器人授权
                || alipayDetail.getType().intValue() == AlipayTypeEnum.DEVICE_MOBILE_AUTH.getId()       //移动端机器人授权
        ){//机器人授权
            dealDeviceAuthBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.PRODUCT_AUTH.getId().intValue()){//购买产品功能模块
            dealProductAuthBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.KUAIZHAN_DOMIAN_BUY.getId().intValue()){//快站域名购买
            dealKuaiZhanDomainBuyBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.KUAIZHAN_DOMIAN_REBUY.getId().intValue()){//快站域名续费
            dealKuaiZhanDomainRebuyBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.BALANCE_RECHARGE.getId().intValue()){//账户余额充值
            dealRechargeBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.DEVICE_WXPUB_AUTH.getId().intValue()){//购买微信公众号授权
            dealWxpubAuthBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.DEVICE_WXWORK_AUTH.getId().intValue()){//购买企业微信授权
            dealWxworkDeviceAuthBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.DEVICE_TIKTOK_AUTH.getId().intValue()){//购买抖音设备授权
            dealTiktokDeviceAuthBunisess(alipayDetail);
        }else if(alipayDetail.getType().intValue() == AlipayTypeEnum.DING_WARNING_GROUP_MSG_BUY.getId().intValue()){//购买顶顶报警群消息
            dealDingWarningGroupBuyMsgBunisess(alipayDetail);
        }
    }

    /**
     * 处理机器人添加移动端业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealDeviceAddBunisess(AlipayDetail alipayDetail){

        if(true){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该功能已经暂停使用");
        }

        Integer now = DateUtil.getNowTime();
        DeviceAddBusinessInfo deviceAddBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), DeviceAddBusinessInfo.class);
        if(deviceAddBusinessInfo != null){

            Merchant merchant = merchantMapper.selectById(alipayDetail.getMerId());
            if(merchant == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
            }

            //机器人类型id
            Integer deviceTypeId = deviceAddBusinessInfo.getDeviceTypeId();
            if(deviceTypeId == null){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            if(deviceTypeId.intValue() != DeviceTypeEnum.DT_ANDROID_WECHAT.getId().intValue()){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //机器人类型key
            String deviceTypeKey = DeviceTypeEnum.getById(deviceTypeId).getKey();

            //机器人wxid
            String deviceId = deviceAddBusinessInfo.getDeviceId();
            if(StringUtils.isBlank(deviceId)){
              throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceAddBusinessInfo.getAuthType();
            if(authType == null){
              throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //授权数量
            Integer quantity = deviceAddBusinessInfo.getQuantity();
            if(quantity == null){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //添加机器人只能购买全包套餐
            DeviceProduct deviceProduct_add = deviceProductMapper.selectByCode(DeviceProductEnum.ALL.getValue());
            if(deviceProduct_add == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置全包套餐");
            }

            //List<String> productCodeList = JSONObject.parseArray(deviceProduct_add.getCodes(), String.class);
            //从枚举中获取关联的产品
            DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceProduct_add.getCode());
            List<String> productCodeList = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
            if(productCodeList == null || productCodeList.size() == 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统全包套餐还没配置包含产品信息");
            }

            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;
            //新的到期时间
            Integer expired_time = 0;

            //本次授权开始时间默认为现在
            Integer begin_time = now;

            //设备号不为空，则开始时间为数据库中最早的授权时间
            if(StringUtils.isNotBlank(deviceId)){
                begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);
            }

            if (deviceAddBusinessInfo.getAuthType().intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                //新的到期时间=现在+月数*30天*24小时*3600秒
                expired_time = begin_time + quantity * 30 * 24 * 3600;
                quantity_db = quantity;
            }else{//按年购买
                //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                quantity_db = quantity * 12;
            }

            //查询整个数据库当中正在使用的该微信id
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectByDeviceId(deviceId);
            if(deviceWechatInfo != null){
                //该机器人不属于自己运营商，则提示错误
                if(deviceWechatInfo.getMerId().longValue() != alipayDetail.getMerId().longValue()){
                   throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
                }
            }

            //选择该运营商默认配置方案
            ConfigPlan configPlan = configPlanMapper.selectByIsDefault(alipayDetail.getMerId(),  deviceAddBusinessInfo.getDeviceType());
            if(configPlan == null){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //是否新增机器人
            if(deviceWechatInfo == null ){//机器人为空，未还添加，则先添加机器人，默认配置方案
                //添加机器人
                deviceWechatInfo = new DeviceWechatInfo();
                deviceWechatInfo.setId(IdWorker.getId());
                deviceWechatInfo.setMerId(alipayDetail.getMerId());
                deviceWechatInfo.setDeviceId(deviceAddBusinessInfo.getDeviceId());
                //选择该运营商默认配置方案
                deviceWechatInfo.setConfigId(configPlan.getId());
                deviceWechatInfo.setRecvmsgType(deviceAddBusinessInfo.getDeviceTypeId());
                deviceWechatInfo.setDelStatus(DeleteStatusEnum.VALID.getId());//有效
                deviceWechatInfo.setCreateTime(now);
                deviceWechatInfo.setUpdateTime(now);
                //添加机器人
                deviceWechatInfoMapper.insert(deviceWechatInfo);

                //需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
                if (configPlan.getOtherId() != null) {
                    SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), alipayDetail.getMerId());
                    if (sysPlugin != null) {
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWechatInfo.getId()), sysPlugin.getData());
                    }
                }
            }

            //查询all产品的价格
            DevicePrice devicePrice_all = devicePriceMapper.selectByAuthType(authType, DeviceProductEnum.ALL.getValue(), DeviceTypeEnum.DT_PC_WECHAT_VALUE);
            if(devicePrice_all == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置所有产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_all.getPrice());

            //分别查询ALL产品包含的产品的总价格
            Double price_total = 0.00D;
            for(String productCode : productCodeList){
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                if(devicePrice == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }

            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);

            //封装机器人授权信息
            List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();

            //新增加时，只能买全包，计算是否需要补差价
            for (String productCode : productCodeList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(authType);
                deviceProductAuth.setExpireTime(expired_time);
                deviceProductAuth.setProductCode(productCode);
                deviceProductAuthList.add(deviceProductAuth);

                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                if (devicePrice == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置个人微信机器人手机端购买价格");
                }

                //产品单价
                Double product_price = Tools.getDouble(devicePrice.getPrice());
                //计算优惠后的产品单价 = 单价- 单价/总价 * 总优惠价
                Double product_price_discount = Math.sub(product_price, Math.mul(Math.div(product_price, price_total), price_discount, 2));

                //总金额=单价*购买时间数
                Double amount = Math.mul(product_price_discount, quantity, 2);
                //查询旧授权
                DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                //还未授权
                if (deviceAuth == null) {
                    //封装产品授权记录
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(deviceWechatInfo.getMerId());
                    deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                    deviceAuthDetail.setDeviceType(deviceAddBusinessInfo.getDeviceType());
                    deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                    deviceAuthDetail.setProductCode(productCode);
                    deviceAuthDetail.setAuthType(authType);
                    deviceAuthDetail.setQuantity(quantity_db);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                    deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                    deviceAuthDetail.setRemark("支付宝支付");
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetail.setAmount(amount);
                    deviceAuthDetail.setBeginTime(begin_time);
                    deviceAuthDetail.setExpireTime(expired_time);
                    //插入授权数据明细
                    deviceAuthDetailMapper.insert(deviceAuthDetail);

                    //添加机器人授权表
                    deviceAuth = new DeviceAuth();
                    deviceAuth.setId(IdWorker.getId());
                    deviceAuth.setDeviceId(deviceWechatInfo.getDeviceId());
                    deviceAuth.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceAuth.setDeviceType(deviceTypeKey);
                    deviceAuth.setDeviceTypeId(deviceTypeId);
                    deviceAuth.setAuthType(authType);
                    deviceAuth.setProductCode(productCode);
                    //新授权，到期时间从今天开始算
                    deviceAuth.setExpireTime(expired_time);
                    deviceAuth.setCreateTime(now);
                    deviceAuth.setUpdateTime(now);
                    deviceAuthMapper.insert(deviceAuth);

                } else { //授权存在，需判断授权的结束时间
                    //旧到期时间
                    Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                    //判断旧授权是否已经过期，
                    if (old_expireTime <= now) { //已经过期
                        //封装产品授权记录
                        DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                        deviceAuthDetail.setId(IdWorker.getId());
                        deviceAuthDetail.setMerId(deviceWechatInfo.getMerId());
                        deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceAuthDetail.setDeviceType(deviceTypeKey);
                        deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                        deviceAuthDetail.setProductCode(productCode);
                        deviceAuthDetail.setAuthType(authType);
                        deviceAuthDetail.setQuantity(quantity_db);
                        deviceAuthDetail.setPayTime(now);
                        deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                        deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                        deviceAuthDetail.setRemark("支付宝支付");
                        deviceAuthDetail.setCreateTime(now);
                        deviceAuthDetail.setUpdateTime(now);
                        deviceAuthDetail.setAmount(amount);
                        deviceAuthDetail.setBeginTime(begin_time);
                        deviceAuthDetail.setExpireTime(expired_time);
                        //插入授权数据明细
                        deviceAuthDetailMapper.insert(deviceAuthDetail);

                        //更新授权记录
                        deviceAuth.setExpireTime(expired_time);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);

                        //旧到期时间大于当前时间，且小于授权结束时间，则补差价
                    } else if(old_expireTime > now && old_expireTime < expired_time){

                        //需要补差价
                        Double differenceAmount = 0.00D;
                        //减去当前的时间，除以3600秒，再除以24小时取整，即是相差的天数
                        Double days = Math.div((old_expireTime - begin_time), 3600 *24,2 );
                        if (deviceAuth.getAuthType().intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId()) {//按月购买的
                            differenceAmount = Math.mul(Math.div(product_price_discount, 30), days, 2);
                        } else {
                            differenceAmount = Math.mul(Math.div(product_price_discount, 360), days, 2);
                        }
                        //单产品支付的金额
                        amount = Math.sub(amount, differenceAmount);

                        //封装产品授权记录
                        DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                        deviceAuthDetail.setId(IdWorker.getId());
                        deviceAuthDetail.setMerId(deviceWechatInfo.getMerId());
                        deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceAuthDetail.setDeviceType(deviceTypeKey);
                        deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                        deviceAuthDetail.setProductCode(productCode);
                        deviceAuthDetail.setAuthType(authType);
                        deviceAuthDetail.setQuantity(quantity_db);
                        deviceAuthDetail.setPayTime(now);
                        deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                        deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                        deviceAuthDetail.setRemark("支付宝支付");
                        deviceAuthDetail.setCreateTime(now);
                        deviceAuthDetail.setUpdateTime(now);
                        deviceAuthDetail.setAmount(amount);
                        deviceAuthDetail.setBeginTime(begin_time);
                        deviceAuthDetail.setExpireTime(expired_time);
                        //插入授权数据明细
                        deviceAuthDetailMapper.insert(deviceAuthDetail);
                        //更新授权记录
                        deviceAuth.setExpireTime(expired_time);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);
                    }
                }
            }

            //添加redis缓存-机器人所属运营商
            Merchant device_merchant = new Merchant();
            device_merchant.setId(merchant.getId());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MERCHANT.getKey(), deviceWechatInfo.getDeviceId()), Tools.getStrEmpty(JSONObject.toJSONString(device_merchant)));

            //更新redis
            if(deviceAddBusinessInfo.getDeviceTypeId().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()){//个人PC端
                Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
                if(object != null){ //修改
                    DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(object.toString(), DeviceInfoPcWeChatCacheDto.class);
                    if(deviceInfoPcWeChatCacheDto != null){
                        deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                    }
                    //更新移动端机器人redis
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
                }else{//新增
                    DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = new DeviceInfoPcWeChatCacheDto();
                    deviceInfoPcWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
                    deviceInfoPcWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                    deviceInfoPcWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceInfoPcWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                    deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                    if(deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()){ //PC端接收消息
                        deviceInfoPcWeChatCacheDto.setMsgHandler(1); //接收消息
                    }else{
                        deviceInfoPcWeChatCacheDto.setMsgHandler(0); //不接受消息
                    }

                    //更新移动端机器人redis
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
                }
            }else if(deviceAddBusinessInfo.getDeviceTypeId().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()){//个人移动端
                Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
                if(object != null) { //修改
                    DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(object.toString(), DeviceInfoMobileWeChatCacheDto.class);
                    if(deviceInfoMobileWeChatCacheDto != null){
                        deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                    }
                    //更新移动端机器人redis
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));

                }else{
                    DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = new DeviceInfoMobileWeChatCacheDto();
                    deviceInfoMobileWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
                    deviceInfoMobileWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                    deviceInfoMobileWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceInfoMobileWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                    deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                    if(deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()){ //手机端接收消息
                        deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
                    }else{
                        deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
                    }
                    //更新移动端机器人redis
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
                }
            }

            //异步执行给机器人移动端APP授权
            deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWechatInfo.getDeviceId(), deviceWechatInfo.getRecvmsgType());
        }
    }

    /**
     * 处理机器人授权业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealDeviceAuthBunisess(AlipayDetail alipayDetail){
        Integer now = DateUtil.getNowTime();
        DeviceAuthBusinessInfo deviceAuthBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), DeviceAuthBusinessInfo.class);
        if(deviceAuthBusinessInfo != null){

            //购买产品
            String productCode_auth = deviceAuthBusinessInfo.getProductCode();
            if(StringUtils.isBlank(productCode_auth)){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            DeviceProduct deviceProduct_auth = deviceProductMapper.selectByCode(productCode_auth);
            if(deviceProduct_auth == null){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //List<String> productCodeList = JSONObject.parseArray(deviceProduct_auth.getCodes(), String.class);
            //从枚举中获取关联的产品
            DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceProduct_auth.getCode());
            List<String> productCodeList = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
            if(productCodeList == null || productCodeList.size() == 0){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //机器人类型id
            Integer deviceTypeId = deviceAuthBusinessInfo.getDeviceTypeId();
            if(deviceTypeId == null){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //机器人类型key
            String deviceTypeKey = DeviceTypeEnum.getById(deviceTypeId).getKey();

            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceAuthBusinessInfo.getAuthType();
            if(authType == null){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //查询产品的总价格
            DevicePrice devicePrice_buy = devicePriceMapper.selectByAuthType(authType, productCode_auth, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
            if(devicePrice_buy == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_buy.getPrice());
            //分别查询该产品包含的产品的总价格
            Double price_total = 0.00D;
            for(String productCode : productCodeList){
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                if(devicePrice == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }
            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);

            //授权数量
            Integer quantity = deviceAuthBusinessInfo.getQuantity();
            if(quantity == null){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;
            //新的到期时间
            Integer expired_time = 0;

            //取出机器人列表
            List<Long> idList = deviceAuthBusinessInfo.getDeviceUniqueIdList();
            for (Long deviceUniqueId : idList){
                DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceUniqueId, alipayDetail.getMerId());
                if(deviceWechatInfo == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
                }

                String deviceId = deviceWechatInfo.getDeviceId();

                //本次授权开始时间默认为现在
                Integer begin_time = now;

                //查询该设备最早授权时间,如果不为空，则取最早授权时间为本次授权开始时间
                begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);

                //选择全包套餐包时的到期时间，如果单个基础包购买，则另外判断到期时间
                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                    //新的到期时间=现在+月数*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 30 * 24 * 3600;
                    quantity_db = quantity;
                }else{//按年购买
                    //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                    quantity_db = quantity * 12;
                }

                //判断购买的产品类型（全包类型需要补差价）
                if(productCodeList.size() == 1){ //单个基础包，则需重新设置到期时间，直接时间累加
                    Integer beginTime_one = 0;
                    Integer expireTime_one = 0;
                    String productCode = productCodeList.get(0);

                    //添加机器人授权表-如果没有则新增，有则修改
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceWechatInfo.getDeviceId(), productCode);
                    if(deviceAuth != null){//修改
                        //判断旧到期时间是否已经过期
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        if(old_expireTime <= now){//已经到期，则从今天开始算
                            beginTime_one = now;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }else{
                            beginTime_one = old_expireTime;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);
                    }else{
                        deviceAuth = new DeviceAuth();
                        deviceAuth.setId(IdWorker.getId());
                        deviceAuth.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceAuth.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceAuth.setDeviceType(deviceTypeKey);
                        deviceAuth.setDeviceTypeId(deviceTypeId);
                        deviceAuth.setProductCode(productCode);
                        beginTime_one = now;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setCreateTime(now);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.insert(deviceAuth);
                    }

                    //添加机器人授权明细表
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(alipayDetail.getMerId());
                    deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                    deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                    deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                    deviceAuthDetail.setProductCode(productCode);
                    deviceAuthDetail.setAuthType(authType);
                    deviceAuthDetail.setQuantity(quantity_db); //试用为0
                    deviceAuthDetail.setBeginTime(beginTime_one);
                    deviceAuthDetail.setExpireTime(expireTime_one);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                    deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                    deviceAuthDetail.setAmount(alipayDetail.getAmount());
                    deviceAuthDetail.setRemark("支付宝支付");
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetailMapper.insert(deviceAuthDetail);
                }else{ //全包产品
                    for (String productCode : productCodeList) {

                        //查询旧授权
                        DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceWechatInfo.getDeviceId(), productCode);
                        //还未授权
                        if (deviceAuth == null) {

                            //封装产品授权记录
                            DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                            deviceAuthDetail.setId(IdWorker.getId());
                            deviceAuthDetail.setMerId(alipayDetail.getMerId());
                            deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                            deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                            deviceAuthDetail.setDeviceType(deviceTypeKey);
                            deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                            deviceAuthDetail.setProductCode(productCode);
                            deviceAuthDetail.setAuthType(authType);
                            deviceAuthDetail.setQuantity(quantity_db);
                            deviceAuthDetail.setPayTime(now);
                            deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                            deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                            deviceAuthDetail.setRemark("支付宝支付");
                            deviceAuthDetail.setCreateTime(now);
                            deviceAuthDetail.setUpdateTime(now);
                            deviceAuthDetail.setAmount(alipayDetail.getAmount());
                            deviceAuthDetail.setBeginTime(begin_time);
                            deviceAuthDetail.setExpireTime(expired_time);
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail);

                            //插入授权数据
                            //添加机器人授权表
                            deviceAuth = new DeviceAuth();
                            deviceAuth.setId(IdWorker.getId());
                            deviceAuth.setDeviceId(deviceWechatInfo.getDeviceId());
                            deviceAuth.setDeviceUniqueId(deviceWechatInfo.getId());
                            deviceAuth.setDeviceType(deviceTypeKey);
                            deviceAuth.setDeviceTypeId(deviceTypeId);
                            deviceAuth.setAuthType(authType);
                            deviceAuth.setProductCode(productCode);
                            //新授权，到期时间从今天开始算
                            deviceAuth.setExpireTime(expired_time);
                            deviceAuth.setCreateTime(now);
                            deviceAuth.setUpdateTime(now);
                            deviceAuthMapper.insert(deviceAuth);

                        } else { //授权存在，需判断授权的结束时间
                            //旧到期时间
                            Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                            //判断旧授权是否已经过期，
                            if (old_expireTime <= now) { //已经过期
                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(alipayDetail.getMerId());
                                deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(deviceTypeKey);
                                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                                deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                                deviceAuthDetail.setRemark("支付宝支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(alipayDetail.getAmount());
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);

                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);

                                //旧到期时间大于当前时间，且小于授权结束时间，则补差价
                            } else if(old_expireTime > now && old_expireTime < expired_time){

                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(alipayDetail.getMerId());
                                deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(deviceTypeKey);
                                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                                deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                                deviceAuthDetail.setRemark("支付宝支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(alipayDetail.getAmount());
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);
                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);
                            }
                        }
                    }
                }

                //封装机器人授权信息
                List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
                //查询该机器人的所有产品授权信息
                DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
                deviceAuthQuery.setDeviceId(deviceWechatInfo.getDeviceId());
                deviceAuthQuery.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
                if(deviceAuthList != null && deviceAuthList.size() > 0) {
                    for (DeviceAuth deviceAuth : deviceAuthList) {
                        //机器人redis缓存信息-产品授权
                        DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                        deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                        deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                        deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                        deviceProductAuthList.add(deviceProductAuth);
                    }

                    //更新PC端redis
                    Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
                    if(object_pc != null){ //修改
                        DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoPcWeChatCacheDto.class);
                        if(deviceInfoPcWeChatCacheDto != null){
                            deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
                    }else{//新增
                        DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = new DeviceInfoPcWeChatCacheDto();
                        deviceInfoPcWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
                        deviceInfoPcWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceInfoPcWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceInfoPcWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                        deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                        if(deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()){ //PC端接收消息
                            deviceInfoPcWeChatCacheDto.setMsgHandler(1); //接收消息
                        }else{
                            deviceInfoPcWeChatCacheDto.setMsgHandler(0); //不接受消息
                        }
                        //更新PC端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
                    }

                    //更新移动端redis
                    Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
                    if(object_moblie != null) { //修改
                        DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWeChatCacheDto.class);
                        if(deviceInfoMobileWeChatCacheDto != null){
                            deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));

                    }else{
                        DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = new DeviceInfoMobileWeChatCacheDto();
                        deviceInfoMobileWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
                        deviceInfoMobileWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceInfoMobileWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceInfoMobileWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                        deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                        if(deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()){ //手机端接收消息
                            deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
                        }else{
                            deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
                    }
                }

                //异步执行给机器人移动端APP授权
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWechatInfo.getDeviceId(), deviceWechatInfo.getRecvmsgType());
            }
        }
    }

    /**
     * 处理功能产品授权业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealProductAuthBunisess(AlipayDetail alipayDetail){
        Integer now = DateUtil.getNowTime();
        ProductAuthBusinessInfo productAuthBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), ProductAuthBusinessInfo.class);
        if(productAuthBusinessInfo != null){

            //产品编码不能为空
            if(StringUtils.isBlank(productAuthBusinessInfo.getProductCode())){
               throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //单个的金额和月数
            Integer beginTime = now;
            Integer expireTime = now;
            Integer quantity = productAuthBusinessInfo.getQuantity();

            //产品授权表-如果没有则新增，有则修改
            ProductAuth productAuth = productAuthMapper.selectByMerIdAndProductCode(alipayDetail.getMerId(), productAuthBusinessInfo.getProductCode());
            if(productAuth != null){//修改
                productAuth.setAuthType(productAuthBusinessInfo.getAuthType());
                //判断旧到期时间是否已经过期
                Integer old_expireTime = Tools.getInteger(productAuth.getExpireTime());
                if(old_expireTime <= now){//已经到期，则从今天开始算
                    beginTime = now;
                    expireTime = beginTime + quantity * 30 * 24 * 3600;
                }else{
                    beginTime = old_expireTime;
                    expireTime = beginTime + quantity * 30 * 24 * 3600;
                }
                productAuth.setExpireTime(expireTime);
                productAuth.setUpdateTime(now);
                productAuthMapper.updateById(productAuth);
            }else{
                productAuth = new ProductAuth();
                productAuth.setId(IdWorker.getId());
                productAuth.setMerId(alipayDetail.getMerId());
                productAuth.setProductCode(productAuthBusinessInfo.getProductCode());
                productAuth.setAuthType(productAuthBusinessInfo.getAuthType());
                beginTime = now;
                expireTime = beginTime + quantity * 30 * 24 * 3600;
                productAuth.setExpireTime(expireTime);
                productAuth.setCreateTime(now);
                productAuth.setUpdateTime(now);
                productAuthMapper.insert(productAuth);
            }

            //添加产品授权明细表
            ProductAuthDetail productAuthDetail = new ProductAuthDetail();
            productAuthDetail.setId(IdWorker.getId());
            productAuthDetail.setMerId(alipayDetail.getMerId());
            productAuthDetail.setProductCode(productAuthBusinessInfo.getProductCode());
            productAuthDetail.setAuthType(productAuthBusinessInfo.getAuthType());
            productAuthDetail.setQuantity(quantity); //试用为0
            productAuthDetail.setBeginTime(beginTime);
            productAuthDetail.setExpireTime(expireTime);
            productAuthDetail.setPayTime(now);
            productAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
            productAuthDetail.setTradeno(alipayDetail.getTradeno());
            productAuthDetail.setAmount(productAuthBusinessInfo.getAmount());
            productAuthDetail.setRemark("支付宝支付");
            productAuthDetail.setCreateTime(now);
            productAuthDetail.setUpdateTime(now);
            productAuthDetailMapper.insert(productAuthDetail);

        }
    }

    /**
     * 处理快站域名购买业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealKuaiZhanDomainBuyBunisess(AlipayDetail alipayDetail){

        //logger.info("---进入创建站点方法----- alipayDetail={}",JSONObject.toJSONString(alipayDetail));

        Integer now = DateUtil.getNowTime();
        KuaiZhanDomianBuyBusinessInfo kuaiZhanDomianBuyBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), KuaiZhanDomianBuyBusinessInfo.class);
        if(kuaiZhanDomianBuyBusinessInfo != null){

            //单个的金额和月数
            Integer quantity = kuaiZhanDomianBuyBusinessInfo.getQuantity();

            //随机快站二级域名
            String domain = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
            //判断二级域名是否重复，如果重复则一直随机获取,直到数据库没有这个二级域名为止
            Boolean domainRepeatFlag = true;
            while (domainRepeatFlag){
                SysDomain sysDomain_Repeat = sysDomainMapper.selectByDomain(domain, alipayDetail.getMerId());
                if(sysDomain_Repeat == null){
                    domainRepeatFlag = false;
                }else{
                    domain = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
                }
            }
            
            //申请创建站点
            CreateSiteVo createSiteVo = kuaiZhanService.createSite(domain);
            if(createSiteVo == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "创建快站域名失败");
            }

            logger.info("---申请站点成功----- createSiteVo={}",JSONObject.toJSONString(createSiteVo));

            SysDomain sysDomain = new SysDomain();
            sysDomain.setId(IdWorker.getId());
            sysDomain.setMerId(alipayDetail.getMerId());
            sysDomain.setType(1); //快站域名
            sysDomain.setAppKey(sysConfigMapper.selectByKey("kzappkey"));
            sysDomain.setAppSecret(sysConfigMapper.selectByKey("kzappsecret"));
            sysDomain.setSiteId(createSiteVo.getSiteId());
            sysDomain.setSiteName(domain);
            sysDomain.setDomain(domain);
            sysDomain.setSiteDomain("https://" + createSiteVo.getSiteDomain());
            sysDomain.setExpiredTime(now + 31536000); //一年授权
            sysDomain.setStatus(1);
            sysDomain.setShared(0);
            sysDomain.setCreateTime(now);
            sysDomain.setUpdateTime(now);
            sysDomainMapper.insertSelective(sysDomain);

            logger.info("---插入站点数据成功----- sysDomain={}",JSONObject.toJSONString(sysDomain));

            Integer beginTime = now;  //授权开始时间
            Integer expireTime = sysDomain.getExpiredTime(); //授权到期时间
            //添加快站域名购买明细表
            SysDomainDetail sysDomainDetail = new SysDomainDetail();
            sysDomainDetail.setId(IdWorker.getId());
            sysDomainDetail.setMerId(alipayDetail.getMerId());
            sysDomainDetail.setDomainId(sysDomain.getId());
            sysDomainDetail.setAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId());
            sysDomainDetail.setQuantity(quantity); //试用为0
            sysDomainDetail.setBeginTime(beginTime);
            sysDomainDetail.setExpireTime(expireTime);
            sysDomainDetail.setPayTime(now);
            sysDomainDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
            sysDomainDetail.setTradeno(alipayDetail.getTradeno());
            sysDomainDetail.setAmount(kuaiZhanDomianBuyBusinessInfo.getAmount());
            sysDomainDetail.setRemark("支付宝支付");
            sysDomainDetail.setCreateTime(now);
            sysDomainDetail.setUpdateTime(now);
            sysDomainDetailMapper.insert(sysDomainDetail);

            logger.info("---插入站点支付明细成功----- sysDomainDetail={}",JSONObject.toJSONString(sysDomainDetail));

            //关闭域名Https跳转
            //kuaiZhanService.changeDomainHttpsForward(createSiteVo.getSiteId(), domain, false);
            //开通套餐
            Boolean packageFlag = kuaiZhanService.openBusinessPackage(createSiteVo.getSiteId());

            logger.info("---开通套餐成功-----packageFlag={}", JSONObject.toJSONString(packageFlag));

            //更新快站页面JS和发布
            String content = Tools.getStr(sysConfigMapper.selectByKey("kz_page_js"));
            //更新页面JS
            Boolean modifyPageJsFlag = kuaiZhanService.modifyPageJs(createSiteVo.getSiteId(), content);

            logger.info("---更新站点页面JS-----modifyPageJsFlag={}", JSONObject.toJSONString(modifyPageJsFlag));

            //发布快站域名
            PublishSiteVo publishSiteVo = kuaiZhanService.publishSite(createSiteVo.getSiteId());

            logger.info("---发布快站域名----- publishSiteVo={}",JSONObject.toJSONString(publishSiteVo));

            //发布页面
            PublishPageVo publishPageVo = kuaiZhanService.publishPage(createSiteVo.getSiteId());

            logger.info("---发布页面----- publishPageVo={}",JSONObject.toJSONString(publishPageVo));

        }
    }

    /**
     * 处理快站域名续费业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealKuaiZhanDomainRebuyBunisess(AlipayDetail alipayDetail){

        logger.info("---进入续费快站域名方法----- alipayDetail={}",JSONObject.toJSONString(alipayDetail));

        Integer now = DateUtil.getNowTime();
        KuaiZhanDomianRebuyBusinessInfo kuaiZhanDomianRebuyBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), KuaiZhanDomianRebuyBusinessInfo.class);
        if(kuaiZhanDomianRebuyBusinessInfo != null){

            if(kuaiZhanDomianRebuyBusinessInfo.getDomainId() == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付宝续费快站域名，域名id不存在");
            }

            //查询快站域名
            SysDomain sysDomain = sysDomainMapper.selectById(kuaiZhanDomianRebuyBusinessInfo.getDomainId(), alipayDetail.getMerId());
            if(sysDomain == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付宝续费快站域名，域名不存在");
            }
            //单个的金额和月数
            Integer quantity = kuaiZhanDomianRebuyBusinessInfo.getQuantity();

            //判断是否是新的APPkey,如果是新的APPkey。则直接续费,否则走购买新新站覆盖旧的域名信息
            String appKey = sysConfigMapper.selectByKey("kzappkey");
            if(appKey.equals(sysDomain.getAppKey())){
                //开通套餐
                Boolean packageFlag = kuaiZhanService.openBusinessPackage(sysDomain.getSiteId());
                if(packageFlag){
                    logger.info("---支付包支付续费开通快站域名套餐成功-----siteId={}", sysDomain.getSiteId());
                    //刷新域名到期时间
                    sysDomain.setExpiredTime(sysDomain.getExpiredTime() + 31536000);
                    sysDomain.setUpdateTime(now);
                    sysDomainMapper.updateByOldSiteId(sysDomain, sysDomain.getSiteId());

                    //添加快站域名购买明细表
                    SysDomainDetail sysDomainDetail = new SysDomainDetail();
                    sysDomainDetail.setId(IdWorker.getId());
                    sysDomainDetail.setMerId(alipayDetail.getMerId());
                    sysDomainDetail.setDomainId(sysDomain.getId());
                    sysDomainDetail.setAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId());
                    sysDomainDetail.setQuantity(quantity); //试用为0
                    sysDomainDetail.setBeginTime(now);
                    sysDomainDetail.setExpireTime(sysDomain.getExpiredTime());
                    sysDomainDetail.setPayTime(now);
                    sysDomainDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                    sysDomainDetail.setTradeno(alipayDetail.getTradeno());
                    sysDomainDetail.setAmount(kuaiZhanDomianRebuyBusinessInfo.getAmount());
                    sysDomainDetail.setRemark("支付宝支付");
                    sysDomainDetail.setCreateTime(now);
                    sysDomainDetail.setUpdateTime(now);
                    sysDomainDetailMapper.insert(sysDomainDetail);
                }else{
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "续费开通快站域名套餐失败");
                }
            }else{
                //随机快站二级域名
                String domain = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
                //判断二级域名是否重复，如果重复则一直随机获取,直到数据库没有这个二级域名为止
                Boolean domainRepeatFlag = true;
                while (domainRepeatFlag){
                    SysDomain sysDomain_Repeat = sysDomainMapper.selectByDomain(domain, alipayDetail.getMerId());
                    if(sysDomain_Repeat == null){
                        domainRepeatFlag = false;
                    }else{
                        domain = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
                    }
                }

                //申请创建站点
                CreateSiteVo createSiteVo = kuaiZhanService.createSite(domain);
                if(createSiteVo == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "创建快站域名失败");
                }

                logger.info("---申请站点成功----- createSiteVo={}",JSONObject.toJSONString(createSiteVo));

                //把新的站点信息覆盖旧的域名数据
                String oldSiteId  = sysDomain.getSiteId();
                sysDomain.setAppKey(sysConfigMapper.selectByKey("kzappkey"));
                sysDomain.setAppSecret(sysConfigMapper.selectByKey("kzappsecret"));
                sysDomain.setSiteId(createSiteVo.getSiteId());
                sysDomain.setSiteName(domain);
                sysDomain.setDomain(domain);
                sysDomain.setSiteDomain("https://" + createSiteVo.getSiteDomain());
                sysDomain.setExpiredTime(now + 31536000); //一年授权
                sysDomain.setUpdateTime(now);
                sysDomainMapper.updateByOldSiteId(sysDomain, oldSiteId);

                logger.info("---插入站点数据成功----- sysDomain={}",JSONObject.toJSONString(sysDomain));

                Integer beginTime = now;  //授权开始时间
                Integer expireTime = sysDomain.getExpiredTime(); //授权到期时间
                //添加快站域名购买明细表
                SysDomainDetail sysDomainDetail = new SysDomainDetail();
                sysDomainDetail.setId(IdWorker.getId());
                sysDomainDetail.setMerId(alipayDetail.getMerId());
                sysDomainDetail.setDomainId(sysDomain.getId());
                sysDomainDetail.setAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId());
                sysDomainDetail.setQuantity(quantity); //试用为0
                sysDomainDetail.setBeginTime(beginTime);
                sysDomainDetail.setExpireTime(expireTime);
                sysDomainDetail.setPayTime(now);
                sysDomainDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                sysDomainDetail.setTradeno(alipayDetail.getTradeno());
                sysDomainDetail.setAmount(kuaiZhanDomianRebuyBusinessInfo.getAmount());
                sysDomainDetail.setRemark("支付宝支付");
                sysDomainDetail.setCreateTime(now);
                sysDomainDetail.setUpdateTime(now);
                sysDomainDetailMapper.insert(sysDomainDetail);

                logger.info("---插入站点支付明细成功----- sysDomainDetail={}",JSONObject.toJSONString(sysDomainDetail));

                //关闭域名Https跳转
                //kuaiZhanService.changeDomainHttpsForward(createSiteVo.getSiteId(), domain, false);
                //开通套餐
                Boolean packageFlag = kuaiZhanService.openBusinessPackage(createSiteVo.getSiteId());

                logger.info("---开通套餐成功-----packageFlag={}", JSONObject.toJSONString(packageFlag));

                //更新快站页面JS和发布
                String content = Tools.getStr(sysConfigMapper.selectByKey("kz_page_js"));
                //更新页面JS
                Boolean modifyPageJsFlag = kuaiZhanService.modifyPageJs(createSiteVo.getSiteId(), content);

                logger.info("---更新站点页面JS-----modifyPageJsFlag={}", JSONObject.toJSONString(modifyPageJsFlag));

                //发布快站域名
                PublishSiteVo publishSiteVo = kuaiZhanService.publishSite(createSiteVo.getSiteId());

                logger.info("---发布快站域名----- publishSiteVo={}",JSONObject.toJSONString(publishSiteVo));

                //发布页面
                PublishPageVo publishPageVo = kuaiZhanService.publishPage(createSiteVo.getSiteId());

                logger.info("---发布页面----- publishPageVo={}",JSONObject.toJSONString(publishPageVo));
            }
        }
    }

    /**
     * 处理账户充值业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealRechargeBunisess(AlipayDetail alipayDetail){
        Integer now = DateUtil.getNowTime();
        RechargeBusinessInfo rechargeBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), RechargeBusinessInfo.class);

        //查询账户余额
        Merchant merchant = merchantMapper.selectById(alipayDetail.getMerId());

        //账户余额
        Double balance = merchant.getBalance();

        //修改账户余额
        merchant.setBalance(balance + alipayDetail.getAmount());
        merchant.setUpdateTime(now);
        int i = merchantMapper.updateBalance(merchant);
        if(i != 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改账户余额失败");
        }

        //添加账户明细
        MerAccDetail merAccDetail = new MerAccDetail();
        merAccDetail.setId(IdWorker.getId());
        merAccDetail.setMerId(merchant.getId());
        merAccDetail.setOperateType(1);//收入
        merAccDetail.setMoney(merchant.getBalance());
        merAccDetail.setCgMoney(alipayDetail.getAmount());
        merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.BALANCE_RECHARGE.getId()); //账户余额充值
        merAccDetail.setTradeno(alipayDetail.getTradeno());
        merAccDetail.setCreateTime(now);
        merAccDetail.setUpdateTime(now);
        int j = merAccDetailMapper.insert(merAccDetail);
        if(j != 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改账户余额失败");
        }
    }

    /**
     * 处理微信公众号授权业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealWxpubAuthBunisess(AlipayDetail alipayDetail){
        Integer now = DateUtil.getNowTime();
        DeviceAuthBusinessInfo deviceAuthBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), DeviceAuthBusinessInfo.class);
        if(deviceAuthBusinessInfo != null){

            //购买产品
            String productCode_auth = deviceAuthBusinessInfo.getProductCode();
            if(StringUtils.isBlank(productCode_auth)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            DeviceProduct deviceProduct_auth = deviceProductMapper.selectByCode(productCode_auth);
            if(deviceProduct_auth == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //List<String> productCodeList = JSONObject.parseArray(deviceProduct_auth.getCodes(), String.class);
            //从枚举中获取关联的产品
            WxpubDeviceProductEnum wxpubDeviceProductEnum = WxpubDeviceProductEnum.getValue(deviceProduct_auth.getCode());
            List<String> productCodeList = JSONObject.parseArray(wxpubDeviceProductEnum.getCodes(), String.class);
            if(productCodeList == null || productCodeList.size() == 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //机器人类型id
            Integer deviceTypeId = deviceAuthBusinessInfo.getDeviceTypeId();
            if(deviceTypeId == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //机器人类型key
            String deviceTypeKey = DeviceTypeEnum.getById(deviceTypeId).getKey();

            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceAuthBusinessInfo.getAuthType();
            if(authType == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //查询产品的总价格
            DevicePrice devicePrice_buy = devicePriceMapper.selectByAuthType(authType, productCode_auth, DeviceTypeEnum.WX_PUB_VALUE);
            if(devicePrice_buy == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_buy.getPrice());
            //分别查询该产品包含的产品的总价格
            Double price_total = 0.00D;
            for(String productCode : productCodeList){
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.WX_PUB_VALUE);
                if(devicePrice == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }
            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);

            //授权数量
            Integer quantity = deviceAuthBusinessInfo.getQuantity();
            if(quantity == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;
            //新的到期时间
            Integer expired_time = 0;

            //取出机器人列表
            List<Long> idList = deviceAuthBusinessInfo.getDeviceUniqueIdList();
            for (Long deviceUniqueId : idList){
                WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(deviceUniqueId);
                if(wxpubInfoEntity == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
                }

                String deviceId = wxpubInfoEntity.getDeviceId();

                //本次授权开始时间默认为现在
                Integer begin_time = now;

                //查询该设备最早授权时间,如果不为空，则取最早授权时间为本次授权开始时间
                begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);

                //选择全包套餐包时的到期时间，如果单个基础包购买，则另外判断到期时间
                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                    //新的到期时间=现在+月数*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 30 * 24 * 3600;
                    quantity_db = quantity;
                }else{//按年购买
                    //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                    quantity_db = quantity * 12;
                }

                //判断购买的产品类型（全包类型需要补差价）
                if(productCodeList.size() == 1){ //单个基础包，则需重新设置到期时间，直接时间累加
                    Integer beginTime_one = 0;
                    Integer expireTime_one = 0;
                    String productCode = productCodeList.get(0);
                    //查询产品价格
                    DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.WX_PUB_VALUE);
                    if (devicePrice == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置机器人该端的购买价格");
                    }
                    //单个机器人总金额=单价*购买时间数
                    Double amount = Math.mul(Tools.getDouble(devicePrice.getPrice()), quantity, 2);

                    //添加机器人授权表-如果没有则新增，有则修改
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                    if(deviceAuth != null){//修改
                        //判断旧到期时间是否已经过期
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        if(old_expireTime <= now){//已经到期，则从今天开始算
                            beginTime_one = now;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }else{
                            beginTime_one = old_expireTime;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);
                    }else{
                        deviceAuth = new DeviceAuth();
                        deviceAuth.setId(IdWorker.getId());
                        deviceAuth.setDeviceId(wxpubInfoEntity.getDeviceId());
                        deviceAuth.setDeviceUniqueId(wxpubInfoEntity.getId());
                        deviceAuth.setDeviceType(deviceTypeKey);
                        deviceAuth.setDeviceTypeId(deviceTypeId);
                        deviceAuth.setProductCode(productCode);
                        beginTime_one = now;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setCreateTime(now);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.insert(deviceAuth);
                    }

                    //添加机器人授权明细表
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(alipayDetail.getMerId());
                    deviceAuthDetail.setDeviceUniqueId(wxpubInfoEntity.getId());
                    deviceAuthDetail.setDeviceId(wxpubInfoEntity.getDeviceId());
                    deviceAuthDetail.setDeviceType(DeviceTypeEnum.WX_PUB.getKey());
                    deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                    deviceAuthDetail.setProductCode(productCode);
                    deviceAuthDetail.setAuthType(authType);
                    deviceAuthDetail.setQuantity(quantity_db); //试用为0
                    deviceAuthDetail.setBeginTime(beginTime_one);
                    deviceAuthDetail.setExpireTime(expireTime_one);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                    deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                    deviceAuthDetail.setAmount(amount);
                    deviceAuthDetail.setRemark("支付宝支付");
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetailMapper.insert(deviceAuthDetail);
                }else{ //全包产品
                    for (String productCode : productCodeList) {
                        //查询旧授权
                        DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(wxpubInfoEntity.getDeviceId(), productCode);
                        //还未授权
                        if (deviceAuth == null) {
                            //封装产品授权记录
                            DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                            deviceAuthDetail.setId(IdWorker.getId());
                            deviceAuthDetail.setMerId(alipayDetail.getMerId());
                            deviceAuthDetail.setDeviceUniqueId(wxpubInfoEntity.getId());
                            deviceAuthDetail.setDeviceId(wxpubInfoEntity.getDeviceId());
                            deviceAuthDetail.setDeviceType(deviceTypeKey);
                            deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                            deviceAuthDetail.setProductCode(productCode);
                            deviceAuthDetail.setAuthType(authType);
                            deviceAuthDetail.setQuantity(quantity_db);
                            deviceAuthDetail.setPayTime(now);
                            deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                            deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                            deviceAuthDetail.setRemark("支付宝支付");
                            deviceAuthDetail.setCreateTime(now);
                            deviceAuthDetail.setUpdateTime(now);
                            deviceAuthDetail.setAmount(alipayDetail.getAmount());
                            deviceAuthDetail.setBeginTime(begin_time);
                            deviceAuthDetail.setExpireTime(expired_time);
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail);

                            //插入授权数据
                            //添加机器人授权表
                            deviceAuth = new DeviceAuth();
                            deviceAuth.setId(IdWorker.getId());
                            deviceAuth.setDeviceId(wxpubInfoEntity.getDeviceId());
                            deviceAuth.setDeviceUniqueId(wxpubInfoEntity.getId());
                            deviceAuth.setDeviceType(deviceTypeKey);
                            deviceAuth.setDeviceTypeId(deviceTypeId);
                            deviceAuth.setAuthType(authType);
                            deviceAuth.setProductCode(productCode);
                            //新授权，到期时间从今天开始算
                            deviceAuth.setExpireTime(expired_time);
                            deviceAuth.setCreateTime(now);
                            deviceAuth.setUpdateTime(now);
                            deviceAuthMapper.insert(deviceAuth);

                        } else { //授权存在，需判断授权的结束时间
                            //旧到期时间
                            Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                            //判断旧授权是否已经过期，
                            if (old_expireTime <= now) { //已经过期
                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(alipayDetail.getMerId());
                                deviceAuthDetail.setDeviceUniqueId(wxpubInfoEntity.getId());
                                deviceAuthDetail.setDeviceId(wxpubInfoEntity.getDeviceId());
                                deviceAuthDetail.setDeviceType(deviceTypeKey);
                                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                                deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                                deviceAuthDetail.setRemark("支付宝支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(alipayDetail.getAmount());
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);

                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);

                                //旧到期时间大于当前时间，且小于授权结束时间，则补差价
                            } else if(old_expireTime > now && old_expireTime < expired_time){

                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(alipayDetail.getMerId());
                                deviceAuthDetail.setDeviceUniqueId(wxpubInfoEntity.getId());
                                deviceAuthDetail.setDeviceId(wxpubInfoEntity.getDeviceId());
                                deviceAuthDetail.setDeviceType(deviceTypeKey);
                                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                                deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                                deviceAuthDetail.setRemark("支付宝支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(alipayDetail.getAmount());
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);
                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);
                            }
                        }
                    }
                }

                //封装机器人授权信息
                List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
                //查询该机器人的所有产品授权信息
                DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
                deviceAuthQuery.setDeviceId(wxpubInfoEntity.getDeviceId());
                deviceAuthQuery.setDeviceType(DeviceTypeEnum.WX_PUB.getKey());
                List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
                if(deviceAuthList != null && deviceAuthList.size() > 0) {
                    for (DeviceAuth deviceAuth : deviceAuthList) {
                        //机器人redis缓存信息-产品授权
                        DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                        deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                        deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                        deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                        deviceProductAuthList.add(deviceProductAuth);
                    }

                    //保存缓存
                    Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXPUB.getKey(), wxpubInfoEntity.getId()));
                    if(object != null){ //修改
                        DeviceInfoWxpubCacheDto deviceInfoWxpubCacheDto = JSONObject.parseObject(object.toString(), DeviceInfoWxpubCacheDto.class);
                        if(deviceInfoWxpubCacheDto != null){
                            deviceInfoWxpubCacheDto.setDeviceAuths(deviceProductAuthList);
                            if(deviceProductAuthList != null && deviceProductAuthList.size() > 0){
                                deviceInfoWxpubCacheDto.setExpireTime(deviceProductAuthList.get(0).getExpireTime());
                            }
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXPUB.getKey(), wxpubInfoEntity.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxpubCacheDto)));
                    }else{//新增
                        DeviceInfoWxpubCacheDto deviceInfoWxpubCacheDto = new DeviceInfoWxpubCacheDto();
                        deviceInfoWxpubCacheDto.setMerId(wxpubInfoEntity.getMerId());
                        deviceInfoWxpubCacheDto.setWxAppId(wxpubInfoEntity.getWxAppId());
                        deviceInfoWxpubCacheDto.setWxAppSecret(wxpubInfoEntity.getWxAppSecret());
                        deviceInfoWxpubCacheDto.setTarget(wxpubInfoEntity.getTarget());
                        deviceInfoWxpubCacheDto.setConfigId(wxpubInfoEntity.getConfigId());
                        deviceInfoWxpubCacheDto.setDeviceId(wxpubInfoEntity.getDeviceId());
                        deviceInfoWxpubCacheDto.setDeviceUniqueId(wxpubInfoEntity.getId());
                        deviceInfoWxpubCacheDto.setMsgHandler(DeviceTypeEnum.WX_PUB.getId());
                        deviceInfoWxpubCacheDto.setDeviceAuths(deviceProductAuthList);
                        if(deviceProductAuthList != null && deviceProductAuthList.size() > 0){
                            deviceInfoWxpubCacheDto.setExpireTime(deviceProductAuthList.get(0).getExpireTime());
                        }
                        //更新PC端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXPUB.getKey(), wxpubInfoEntity.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxpubCacheDto)));
                    }
                }
            }
        }
    }

    /**
     * 处理企业微信机器人授权业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealWxworkDeviceAuthBunisess(AlipayDetail alipayDetail){
        Integer now = DateUtil.getNowTime();
        DeviceAuthBusinessInfo deviceAuthBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), DeviceAuthBusinessInfo.class);
        if(deviceAuthBusinessInfo != null){

            //购买产品
            String productCode_auth = deviceAuthBusinessInfo.getProductCode();
            if(StringUtils.isBlank(productCode_auth)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            DeviceProduct deviceProduct_auth = deviceProductMapper.selectByCode(productCode_auth);
            if(deviceProduct_auth == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //List<String> productCodeList = JSONObject.parseArray(deviceProduct_auth.getCodes(), String.class);
            //从枚举中获取关联的产品
            WxworkDeviceProductEnum wxworkDeviceProductEnum = WxworkDeviceProductEnum.getValue(deviceProduct_auth.getCode());
            List<String> productCodeList = JSONObject.parseArray(wxworkDeviceProductEnum.getCodes(), String.class);
            if(productCodeList == null || productCodeList.size() == 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //机器人类型id
            Integer deviceTypeId = deviceAuthBusinessInfo.getDeviceTypeId();
            if(deviceTypeId == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //机器人类型key
            String deviceTypeKey = DeviceTypeEnum.getById(deviceTypeId).getKey();

            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceAuthBusinessInfo.getAuthType();
            if(authType == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //查询产品的总价格
            DevicePrice devicePrice_buy = devicePriceMapper.selectByAuthType(authType, productCode_auth, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
            if(devicePrice_buy == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_buy.getPrice());
            //分别查询该产品包含的产品的总价格
            Double price_total = 0.00D;
            for(String productCode : productCodeList){
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                if(devicePrice == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }
            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);

            //授权数量
            Integer quantity = deviceAuthBusinessInfo.getQuantity();
            if(quantity == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;
            //新的到期时间
            Integer expired_time = 0;

            //取出机器人列表
            List<Long> idList = deviceAuthBusinessInfo.getDeviceUniqueIdList();
            for (Long deviceUniqueId : idList){
                DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceUniqueId, alipayDetail.getMerId());
                if(deviceWxworkInfo == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
                }

                String deviceId = deviceWxworkInfo.getDeviceId();

                //本次授权开始时间默认为现在
                Integer begin_time = now;

                //查询该设备最早授权时间,如果不为空，则取最早授权时间为本次授权开始时间
                begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);

                //选择全包套餐包时的到期时间，如果单个基础包购买，则另外判断到期时间
                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                    //新的到期时间=现在+月数*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 30 * 24 * 3600;
                    quantity_db = quantity;
                }else{//按年购买
                    //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                    quantity_db = quantity * 12;
                }

                //判断购买的产品类型（全包类型需要补差价）
                if(productCodeList.size() == 1){ //单个基础包，则需重新设置到期时间，直接时间累加
                    Integer beginTime_one = 0;
                    Integer expireTime_one = 0;
                    String productCode = productCodeList.get(0);

                    //添加机器人授权表-如果没有则新增，有则修改
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceWxworkInfo.getDeviceId(), productCode);
                    if(deviceAuth != null){//修改
                        //判断旧到期时间是否已经过期
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        if(old_expireTime <= now){//已经到期，则从今天开始算
                            beginTime_one = now;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }else{
                            beginTime_one = old_expireTime;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);
                    }else{
                        deviceAuth = new DeviceAuth();
                        deviceAuth.setId(IdWorker.getId());
                        deviceAuth.setDeviceId(deviceWxworkInfo.getDeviceId());
                        deviceAuth.setDeviceUniqueId(deviceWxworkInfo.getId());
                        deviceAuth.setDeviceType(deviceTypeKey);
                        deviceAuth.setDeviceTypeId(deviceTypeId);
                        deviceAuth.setProductCode(productCode);
                        beginTime_one = now;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setCreateTime(now);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.insert(deviceAuth);
                    }

                    //添加机器人授权明细表
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(alipayDetail.getMerId());
                    deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                    deviceAuthDetail.setDeviceType(deviceTypeKey);
                    deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                    deviceAuthDetail.setProductCode(productCode);
                    deviceAuthDetail.setAuthType(authType);
                    deviceAuthDetail.setQuantity(quantity_db); //试用为0
                    deviceAuthDetail.setBeginTime(beginTime_one);
                    deviceAuthDetail.setExpireTime(expireTime_one);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                    deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                    deviceAuthDetail.setAmount(alipayDetail.getAmount());
                    deviceAuthDetail.setRemark("支付宝支付");
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetailMapper.insert(deviceAuthDetail);
                }else{ //全包产品
                    for (String productCode : productCodeList) {
                        //查询旧授权
                        DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceWxworkInfo.getDeviceId(), productCode);
                        //还未授权
                        if (deviceAuth == null) {
                            //封装产品授权记录
                            DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                            deviceAuthDetail.setId(IdWorker.getId());
                            deviceAuthDetail.setMerId(alipayDetail.getMerId());
                            deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                            deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                            deviceAuthDetail.setDeviceType(deviceTypeKey);
                            deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                            deviceAuthDetail.setProductCode(productCode);
                            deviceAuthDetail.setAuthType(authType);
                            deviceAuthDetail.setQuantity(quantity_db);
                            deviceAuthDetail.setPayTime(now);
                            deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                            deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                            deviceAuthDetail.setRemark("支付宝支付");
                            deviceAuthDetail.setCreateTime(now);
                            deviceAuthDetail.setUpdateTime(now);
                            deviceAuthDetail.setAmount(alipayDetail.getAmount());
                            deviceAuthDetail.setBeginTime(begin_time);
                            deviceAuthDetail.setExpireTime(expired_time);
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail);

                            //插入授权数据
                            //添加机器人授权表
                            deviceAuth = new DeviceAuth();
                            deviceAuth.setId(IdWorker.getId());
                            deviceAuth.setDeviceId(deviceWxworkInfo.getDeviceId());
                            deviceAuth.setDeviceUniqueId(deviceWxworkInfo.getId());
                            deviceAuth.setDeviceType(deviceTypeKey);
                            deviceAuth.setDeviceTypeId(deviceTypeId);
                            deviceAuth.setAuthType(authType);
                            deviceAuth.setProductCode(productCode);
                            //新授权，到期时间从今天开始算
                            deviceAuth.setExpireTime(expired_time);
                            deviceAuth.setCreateTime(now);
                            deviceAuth.setUpdateTime(now);
                            deviceAuthMapper.insert(deviceAuth);

                        } else { //授权存在，需判断授权的结束时间
                            //旧到期时间
                            Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                            //判断旧授权是否已经过期，
                            if (old_expireTime <= now) { //已经过期
                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(alipayDetail.getMerId());
                                deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(deviceTypeKey);
                                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                                deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                                deviceAuthDetail.setRemark("支付宝支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(alipayDetail.getAmount());
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);

                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);

                                //旧到期时间大于当前时间，且小于授权结束时间，则补差价
                            } else if(old_expireTime > now && old_expireTime < expired_time){

                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(alipayDetail.getMerId());
                                deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(deviceTypeKey);
                                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                                deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                                deviceAuthDetail.setRemark("支付宝支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(alipayDetail.getAmount());
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);
                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);
                            }
                        }
                    }
                }

                //封装机器人授权信息
                List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
                //查询该机器人的所有产品授权信息
                DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
                deviceAuthQuery.setDeviceId(deviceWxworkInfo.getDeviceId());
                deviceAuthQuery.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
                if(deviceAuthList != null && deviceAuthList.size() > 0) {
                    for (DeviceAuth deviceAuth : deviceAuthList) {
                        //机器人redis缓存信息-产品授权
                        DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                        deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                        deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                        deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                        deviceProductAuthList.add(deviceProductAuth);
                    }

                    //更新redis
                    Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
                    if(object_pc != null){ //修改
                        DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoWxWorkCacheDto.class);
                        if(deviceInfoWxWorkCacheDto != null){
                            deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                            //更新企业微信机器人redis
                            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
                        }
                    }else{//新增
                        DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = new DeviceInfoWxWorkCacheDto();
                        deviceInfoWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
                        deviceInfoWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
                        deviceInfoWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
                        deviceInfoWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
                        deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                        deviceInfoWxWorkCacheDto.setMsgHandler(DeviceTypeEnum.DT_WORK_WECHAT_VALUE); //接收消息
                        if(deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT.getId()){ //PC端接收消息
                            deviceInfoWxWorkCacheDto.setMsgHandler(1); //接收消息
                        }else{
                            deviceInfoWxWorkCacheDto.setMsgHandler(0); //不接受消息
                        }
                        //更新PC端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
                    }

                    //更新移动端redis
                    Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
                    if(object_moblie != null) { //修改
                        DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWxWorkCacheDto.class);
                        if(deviceInfoMobileWxWorkCacheDto != null){
                            deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));

                    }else{
                        DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = new DeviceInfoMobileWxWorkCacheDto();
                        deviceInfoMobileWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
                        deviceInfoMobileWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
                        deviceInfoMobileWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
                        deviceInfoMobileWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
                        deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                        if(deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId()){ //手机端接收消息
                            deviceInfoMobileWxWorkCacheDto.setMsgHandler(1);
                        }else{
                            deviceInfoMobileWxWorkCacheDto.setMsgHandler(0);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
                    }
                }

                //异步执行给机器人移动端APP授权
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWxworkInfo.getDeviceId(), deviceWxworkInfo.getRecvmsgType());
            }
        }
    }

    /**
     * 处理抖音机器人授权业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealTiktokDeviceAuthBunisess(AlipayDetail alipayDetail){
        Integer now = DateUtil.getNowTime();
        DeviceAuthBusinessInfo deviceAuthBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), DeviceAuthBusinessInfo.class);
        if(deviceAuthBusinessInfo != null){

            //购买产品
            String productCode_auth = deviceAuthBusinessInfo.getProductCode();
            if(StringUtils.isBlank(productCode_auth)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            DeviceProduct deviceProduct_auth = deviceProductMapper.selectByCode(productCode_auth);
            if(deviceProduct_auth == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //List<String> productCodeList = JSONObject.parseArray(deviceProduct_auth.getCodes(), String.class);
            //从枚举中获取关联的产品
            TiktokDeviceProductEnum tiktokDeviceProductEnum = TiktokDeviceProductEnum.getValue(deviceProduct_auth.getCode());
            List<String> productCodeList = JSONObject.parseArray(tiktokDeviceProductEnum.getCodes(), String.class);
            if(productCodeList == null || productCodeList.size() == 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //机器人类型id
            Integer deviceTypeId = deviceAuthBusinessInfo.getDeviceTypeId();
            if(deviceTypeId == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //机器人类型key
            String deviceTypeKey = DeviceTypeEnum.getById(deviceTypeId).getKey();

            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceAuthBusinessInfo.getAuthType();
            if(authType == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }

            //查询产品的总价格
            DevicePrice devicePrice_buy = devicePriceMapper.selectByAuthType(authType, productCode_auth, DeviceTypeEnum.TIKTOK_VALUE);
            if(devicePrice_buy == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_buy.getPrice());
            //分别查询该产品包含的产品的总价格
            Double price_total = 0.00D;
            for(String productCode : productCodeList){
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.TIKTOK_VALUE);
                if(devicePrice == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }
            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);

            //授权数量
            Integer quantity = deviceAuthBusinessInfo.getQuantity();
            if(quantity == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
            }
            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;
            //新的到期时间
            Integer expired_time = 0;

            //取出机器人列表
            List<Long> idList = deviceAuthBusinessInfo.getDeviceUniqueIdList();
            for (Long deviceUniqueId : idList){
                DeviceTiktokInfo deviceTiktokInfo = deviceTiktokInfoMapper.selectById(deviceUniqueId, alipayDetail.getMerId());
                if(deviceTiktokInfo == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付失败");
                }

                String deviceId = deviceTiktokInfo.getDeviceId();

                //本次授权开始时间默认为现在
                Integer begin_time = now;

                //查询该设备最早授权时间,如果不为空，则取最早授权时间为本次授权开始时间
                begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);

                //选择全包套餐包时的到期时间，如果单个基础包购买，则另外判断到期时间
                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                    //新的到期时间=现在+月数*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 30 * 24 * 3600;
                    quantity_db = quantity;
                }else{//按年购买
                    //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                    quantity_db = quantity * 12;
                }

                //判断购买的产品类型（全包类型需要补差价）
                if(productCodeList.size() == 1){ //单个基础包，则需重新设置到期时间，直接时间累加
                    Integer beginTime_one = 0;
                    Integer expireTime_one = 0;
                    String productCode = productCodeList.get(0);

                    //添加机器人授权表-如果没有则新增，有则修改
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceTiktokInfo.getDeviceId(), productCode);
                    if(deviceAuth != null){//修改
                        //判断旧到期时间是否已经过期
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        if(old_expireTime <= now){//已经到期，则从今天开始算
                            beginTime_one = now;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }else{
                            beginTime_one = old_expireTime;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);
                    }else{
                        deviceAuth = new DeviceAuth();
                        deviceAuth.setId(IdWorker.getId());
                        deviceAuth.setDeviceId(deviceTiktokInfo.getDeviceId());
                        deviceAuth.setDeviceUniqueId(deviceTiktokInfo.getId());
                        deviceAuth.setDeviceType(deviceTypeKey);
                        deviceAuth.setDeviceTypeId(deviceTypeId);
                        deviceAuth.setProductCode(productCode);
                        beginTime_one = now;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setCreateTime(now);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.insert(deviceAuth);
                    }

                    //添加机器人授权明细表
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(alipayDetail.getMerId());
                    deviceAuthDetail.setDeviceUniqueId(deviceTiktokInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceTiktokInfo.getDeviceId());
                    deviceAuthDetail.setDeviceType(deviceTypeKey);
                    deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                    deviceAuthDetail.setProductCode(productCode);
                    deviceAuthDetail.setAuthType(authType);
                    deviceAuthDetail.setQuantity(quantity_db); //试用为0
                    deviceAuthDetail.setBeginTime(beginTime_one);
                    deviceAuthDetail.setExpireTime(expireTime_one);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                    deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                    deviceAuthDetail.setAmount(alipayDetail.getAmount());
                    deviceAuthDetail.setRemark("支付宝支付");
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetailMapper.insert(deviceAuthDetail);
                }else{ //全包产品
                    for (String productCode : productCodeList) {
                        //查询旧授权
                        DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceTiktokInfo.getDeviceId(), productCode);
                        //还未授权
                        if (deviceAuth == null) {
                            //封装产品授权记录
                            DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                            deviceAuthDetail.setId(IdWorker.getId());
                            deviceAuthDetail.setMerId(alipayDetail.getMerId());
                            deviceAuthDetail.setDeviceUniqueId(deviceTiktokInfo.getId());
                            deviceAuthDetail.setDeviceId(deviceTiktokInfo.getDeviceId());
                            deviceAuthDetail.setDeviceType(deviceTypeKey);
                            deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                            deviceAuthDetail.setProductCode(productCode);
                            deviceAuthDetail.setAuthType(authType);
                            deviceAuthDetail.setQuantity(quantity_db);
                            deviceAuthDetail.setPayTime(now);
                            deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                            deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                            deviceAuthDetail.setRemark("支付宝支付");
                            deviceAuthDetail.setCreateTime(now);
                            deviceAuthDetail.setUpdateTime(now);
                            deviceAuthDetail.setAmount(alipayDetail.getAmount());
                            deviceAuthDetail.setBeginTime(begin_time);
                            deviceAuthDetail.setExpireTime(expired_time);
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail);

                            //插入授权数据
                            //添加机器人授权表
                            deviceAuth = new DeviceAuth();
                            deviceAuth.setId(IdWorker.getId());
                            deviceAuth.setDeviceId(deviceTiktokInfo.getDeviceId());
                            deviceAuth.setDeviceUniqueId(deviceTiktokInfo.getId());
                            deviceAuth.setDeviceType(deviceTypeKey);
                            deviceAuth.setDeviceTypeId(deviceTypeId);
                            deviceAuth.setAuthType(authType);
                            deviceAuth.setProductCode(productCode);
                            //新授权，到期时间从今天开始算
                            deviceAuth.setExpireTime(expired_time);
                            deviceAuth.setCreateTime(now);
                            deviceAuth.setUpdateTime(now);
                            deviceAuthMapper.insert(deviceAuth);

                        } else { //授权存在，需判断授权的结束时间
                            //旧到期时间
                            Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                            //判断旧授权是否已经过期，
                            if (old_expireTime <= now) { //已经过期
                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(alipayDetail.getMerId());
                                deviceAuthDetail.setDeviceUniqueId(deviceTiktokInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceTiktokInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(deviceTypeKey);
                                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                                deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                                deviceAuthDetail.setRemark("支付宝支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(alipayDetail.getAmount());
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);

                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);

                                //旧到期时间大于当前时间，且小于授权结束时间，则补差价
                            } else if(old_expireTime > now && old_expireTime < expired_time){

                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(alipayDetail.getMerId());
                                deviceAuthDetail.setDeviceUniqueId(deviceTiktokInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceTiktokInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(deviceTypeKey);
                                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_ALIPAY.getId());
                                deviceAuthDetail.setTradeno(alipayDetail.getTradeno());
                                deviceAuthDetail.setRemark("支付宝支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(alipayDetail.getAmount());
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);
                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);
                            }
                        }
                    }
                }

                //封装机器人授权信息
                List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
                //查询该机器人的所有产品授权信息
                DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
                deviceAuthQuery.setDeviceId(deviceTiktokInfo.getDeviceId());
                deviceAuthQuery.setDeviceType(DeviceTypeEnum.TIKTOK.getKey());
                List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
                if(deviceAuthList != null && deviceAuthList.size() > 0) {
                    for (DeviceAuth deviceAuth : deviceAuthList) {
                        //机器人redis缓存信息-产品授权
                        DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                        deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                        deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                        deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                        deviceProductAuthList.add(deviceProductAuth);
                    }

                    Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_TIKTOK.getKey(), deviceTiktokInfo.getId()));
                    if(object != null){ //修改
                        DeviceInfoTiktokCacheDto deviceInfoTiktokCacheDto = JSONObject.parseObject(object.toString(), DeviceInfoTiktokCacheDto.class);
                        if(deviceInfoTiktokCacheDto != null){
                            deviceInfoTiktokCacheDto.setDeviceAuths(deviceProductAuthList);
                            //更新移动端机器人redis
                            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_TIKTOK.getKey(), deviceTiktokInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoTiktokCacheDto)));
                        }
                    }else{//新增
                        DeviceInfoTiktokCacheDto deviceInfoTiktokCacheDto = new DeviceInfoTiktokCacheDto();
                        deviceInfoTiktokCacheDto.setMerId(deviceTiktokInfo.getMerId());
                        deviceInfoTiktokCacheDto.setDeviceId(deviceTiktokInfo.getDeviceId());
                        deviceInfoTiktokCacheDto.setDeviceUniqueId(deviceTiktokInfo.getId());
                        deviceInfoTiktokCacheDto.setConfigId(deviceTiktokInfo.getConfigId());
                        deviceInfoTiktokCacheDto.setDeviceAuths(deviceProductAuthList);
                        deviceInfoTiktokCacheDto.setMsgHandler(1); //接收消息
                        //更新PC端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_TIKTOK.getKey(), deviceTiktokInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoTiktokCacheDto)));
                    }

                }
            }
        }
    }

    /**
     * 处理顶顶报警群购买消息业务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alipayDetail
     * @return null
     */
    public void dealDingWarningGroupBuyMsgBunisess(AlipayDetail alipayDetail){
        Integer now = DateUtil.getNowTime();
        DingWarningGroupMsgBuyBusinessInfo dingWarningGroupMsgBuyBusinessInfo = JSONObject.parseObject(alipayDetail.getBusinessInfo(), DingWarningGroupMsgBuyBusinessInfo.class);
        if(dingWarningGroupMsgBuyBusinessInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "封装钉钉报警群购买消息业务对象有误");
        }

        //查询产品的总价格
        DingWarningGroup dingWarningGroup = dingWarningGroupMapper.queryDingWarningGroupById(dingWarningGroupMsgBuyBusinessInfo.getDingWarningGroupId());
        if(dingWarningGroup == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该顶顶报警群信息");
        }

        //修改钉钉群报警消息购买数(当前付费总数+购买总数)
        dingWarningGroup.setPayMsg(dingWarningGroup.getPayMsg() + dingWarningGroupMsgBuyBusinessInfo.getMsgTotal());
        dingWarningGroup.setPayMsgUpdateTime(now);
        dingWarningGroup.setUpdateTime(now);
        int i = dingWarningGroupMapper.updatePayMsg(dingWarningGroup);
        if(i != 1) {
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改顶顶报警群信息购买数失败");
        }

        //增加钉钉群报警消息购买明细
        DingWarningGroupDetail dingWarningGroupDetail = new DingWarningGroupDetail();
        dingWarningGroupDetail.setId(IdWorker.getId());
        dingWarningGroupDetail.setMerId(alipayDetail.getMerId());
        dingWarningGroupDetail.setDingWarningGroupId(dingWarningGroup.getId());
        dingWarningGroupDetail.setTradeno(alipayDetail.getTradeno());
        dingWarningGroupDetail.setType(1);    //付费
        dingWarningGroupDetail.setMsgNum(dingWarningGroupMsgBuyBusinessInfo.getMsgTotal());
        dingWarningGroupDetail.setCreateTime(now);
        dingWarningGroupDetail.setUpdateTime(now);
        int j = dingWarningGroupDetailMapper.insert(dingWarningGroupDetail);
        if(j != 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "插入顶顶报警群信息购买明细失败");
        }
    }

    /**
     * 在线查询支付宝支付结果
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tradeno
     * @return null
     */
    @Transactional
    public void alipayTradeQuery(String tradeno){
        //返回支付页面地址
        String aliPayAppId = sysConfigMapper.selectByKey("aliPayAppId");
        String aliPayAppPriKey = sysConfigMapper.selectByKey("aliPayAppPriKey");
        try{

            //查询支付宝支付交易记录
            AlipayDetail alipayDetail = alipayDetailMapper.selectByTradeno(tradeno);
            if(alipayDetail == null ){
                return;
            }

            if(alipayDetail.getStatus().intValue() == AlipayStatusEnum.WAIT_BUYER_PAY.getId().intValue()){ //等待支付状态

                //构造client(证书访问)
                CertAlipayRequest certAlipayRequest = aliPayConfig.getCertAlipayRequest(aliPayAppId, aliPayAppPriKey);
                //客户端订单客户端
                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

                Integer now = DateUtil.getNowTime();

                if(now - alipayDetail.getCreateTime().intValue() < 24*3600 ){ //等待时间小于当天之内的订单

                    AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                    JSONObject bizContent = new JSONObject();
                    bizContent.put("out_trade_no", tradeno);
                    request.setBizContent(bizContent.toString());
                    AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
                    //logger.info("---在线查询支付宝交易记录结果---response={}, trandeno={}",JSONObject.toJSONString(response), tradeno);
                    if(response.isSuccess()){//查询成功
                        AlipayTradeQueryVo alipayTradeQueryVo = JSONObject.parseObject(JSONObject.toJSONString(response), AlipayTradeQueryVo.class);
                        //logger.info(JSONObject.toJSONString(alipayTradeQueryVo));
                        if(Tools.getStr(alipayTradeQueryVo.getTradeStatus()).equals("TRADE_SUCCESS")){ //交易成功
                            if(alipayDetail.getStatus().intValue() == AlipayStatusEnum.WAIT_BUYER_PAY.getId()){
                                dealBunisess(alipayDetail);//处理支付业务功能
                            }
                            //修改支付宝账单状态为付款成功状态
                            alipayDetail.setSubCode(alipayTradeQueryVo.getSubCode());
                            alipayDetail.setSubMsg(alipayTradeQueryVo.getSubMsg());
                            alipayDetail.setAliTradeNo(alipayTradeQueryVo.getTradeNo());
                            alipayDetail.setSellerId("");
                            alipayDetail.setStatus(AlipayStatusEnum.TRADE_SUCCESS.getId());
                            alipayDetail.setUpdateTime(now);
                            int i = alipayDetailMapper.updateByIdSelective(alipayDetail);
                            if(i != 1){
                                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改支付宝交易记录失败");
                            }
                        }else if(Tools.getStr(alipayTradeQueryVo.getTradeStatus()).equals("TRADE_CLOSED")){ //交易关闭
                            alipayDetail.setStatus(AlipayStatusEnum.TRADE_CLOSED.getId());
                            alipayDetail.setUpdateTime(now);
                            alipayDetail.setSubCode("TRADE_HAS_CLOSE");
                            alipayDetail.setSubMsg("交易已经关闭");
                            int i = alipayDetailMapper.updateByIdSelective(alipayDetail);
                            if(i != 1){
                                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改支付宝交易记录失败");
                            }
                        }
                    } else {
//                        logger.info("查询支付宝交易记录结果:tradeno={},error={}", tradeno, response.getSubMsg());
//
//                        if("ACQ.TRADE_NOT_EXIST".equals(response.getSubCode())){ //交易不存在，关闭此订单
//                            //关闭支付宝订单
//                            alipayDetail.setStatus(AlipayStatusEnum.TRADE_CLOSED.getId());
//                            alipayDetail.setUpdateTime(now);
//                            alipayDetail.setSubCode(response.getSubCode());
//                            alipayDetail.setSubMsg(response.getSubMsg());
//                            int i = alipayDetailMapper.updateByIdSelective(alipayDetail);
//                            if(i != 1){
//                                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改支付宝交易记录失败");
//                            }
//                            logger.info("关闭支付宝支付记录,tradeno={},error={}", tradeno, response.getSubMsg());
//                        }
                    }
                }else{
                    //关闭支付宝订单
                    alipayDetail.setStatus(AlipayStatusEnum.TRADE_CLOSED.getId());
                    alipayDetail.setUpdateTime(now);
                    alipayDetail.setSubCode("TRADE_HAS_CLOSE");
                    alipayDetail.setSubMsg("交易已经关闭");
                    int i = alipayDetailMapper.updateByIdSelective(alipayDetail);
                    if(i != 1){
                        throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改支付宝交易记录失败");
                    }
                    try{
                        //关闭支付宝交易记录
                        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
                        JSONObject bizContent = new JSONObject();
                        bizContent.put("out_trade_no", alipayDetail.getTradeno());
                        request.setBizContent(bizContent.toString());
                        AlipayTradeCloseResponse response = alipayClient.certificateExecute(request);
                    }catch (Exception e){

                    }
                }
            }
        }catch (Exception e){
            logger.error("调用支付宝生成账单失败,error={}", e.getMessage());
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, e.getMessage());
        }
    }

}
